<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2-处理ajax响应</title>
    <style>
        #box {
            width: 200px;
            height: 200px;
            border: 1px solid #666;
        }
    </style>
</head>

<body>
    <button id="textBtn">AJAX 获取Text</button>
    <button id="jsonBtn">AJAX 获取JSON</button>

    <div id="box"></div>

    <script>
        document.querySelector('#textBtn').onclick = () => {
            // 发送get请求到服务器
            const xhr = new XMLHttpRequest()
            xhr.open('GET', 'http://127.0.0.1:8081/text-server')
            xhr.send()
            // 监听xhr状态
            xhr.onreadystatechange = () => {
                console.log('onreadystatechange', xhr.readyState)
                if (xhr.readyState === 4) {
                    document.querySelector('#box').innerHTML = xhr.responseText
                }
            }
        }

        document.querySelector('#jsonBtn').onclick = () => {
            // 发送get请求到服务器
            const xhr = new XMLHttpRequest()
            xhr.open('GET', 'http://127.0.0.1:8081/json-server')
            xhr.send()
            // 监听xhr状态
            xhr.onreadystatechange = () => {
                console.log('onreadystatechange', xhr.readyState)
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status <= 299) {
                        console.log(xhr.responseText)
                        document.querySelector('#box').innerHTML = xhr.responseText
                    } else {
                        alert('请求失败， status=' + xhr.status)
                    }
                }
            }
        }


    </script>
</body>

</html>